package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysWechatBind;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysWechatBindService sysWechatBindService;
    
    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private TokenService tokenService;

    /**
     * 通过openId查询关联的用户信息
     * @param requestData 请求数据，包含openId
     * @return 关联的用户信息列表
     */
    @Anonymous
    @PostMapping("/getUsersByOpenId")
    public AjaxResult getUsersByOpenId(@RequestBody Map<String, String> requestData)
    {
        try {
            String openId = requestData.get("openId");
            if (StringUtils.isEmpty(openId)) {
                return error("OpenID不能为空");
            }

            // 通过openId查询绑定关系
            SysWechatBind queryBind = new SysWechatBind();
            queryBind.setOpenId(openId);
            queryBind.setBindStatus(1); // 只查询已绑定状态的记录
            List<SysWechatBind> bindList = sysWechatBindService.selectSysWechatBindList(queryBind);

            if (bindList == null || bindList.isEmpty()) {
                return AjaxResult.success("未找到绑定的用户").put("data", new ArrayList<>());
            }

            // 根据绑定关系查询用户信息
            List<Map<String, Object>> userList = new ArrayList<>();
            for (SysWechatBind bind : bindList) {
                SysUser user = userService.selectUserById(Long.valueOf(bind.getUserId()));
                if (user != null && "0".equals(user.getStatus())) { // 只返回正常状态的用户
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("userId", user.getUserId());
                    userInfo.put("userName", user.getUserName());
                    userInfo.put("nickName", user.getNickName());
                    userInfo.put("phonenumber", user.getPhonenumber());
                    userInfo.put("avatar", user.getAvatar());
                    userInfo.put("deptName", user.getDept() != null ? user.getDept().getDeptName() : "");
                    userInfo.put("bindInfo", bind); // 包含绑定信息
                    userList.add(userInfo);
                }
            }

            return AjaxResult.success("查询成功").put("data", userList);
        } catch (Exception e) {
            logger.error("通过openId查询用户信息异常", e);
            return error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setLoginCountStatus("1");//新增用户的时候默认设置为是第一次登录
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
    @GetMapping("/deptTree2")
    public AjaxResult deptTree2(SysDept dept)
    {
        return success(deptService.selectDeptTreeList2(dept));
    }

    @GetMapping("/deptTree1")
    public AjaxResult deptTree1(SysDept dept)
    {
        return success(deptService.selectDeptTreeList1(dept));
    }
    @GetMapping("/deptTree3")
    public AjaxResult deptTree3(SysDept dept)
    {
        return success(deptService.selectDeptTreeList3(dept));
    }

    @GetMapping("/selectVXUserCount")
    public AjaxResult selectVXUserCount(SysUser user)
    {
        JSONObject jsonObject = userService.selectVXUserCount(user);
        return AjaxResult.success(jsonObject);
    }

    @GetMapping("/selectUserByPhone")
    public AjaxResult selectUserByPhone(){
        String phonenumber = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        return AjaxResult.success(userService.selectUserByPhone(phonenumber));
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateLoginStatus")
    public AjaxResult updateLoginStatus(@Validated @RequestBody SysUser user)
    {
        return AjaxResult.success(userService.updateLoginStatus(user));
    }

    /**
     * 生成临时秘钥接口
     * @param requestData 包含token的请求数据
     * @return 返回临时秘钥
     */
    @Anonymous
    @PostMapping("/generateTempSecret")
    public AjaxResult generateTempSecret(@RequestBody Map<String, String> requestData) {
        try {
            String token = requestData.get("token");
            if (StringUtils.isEmpty(token)) {
                return error("Token不能为空");
            }

            // 直接从数据库中根据auth_token查询用户
            SysUser user = userService.selectUserByAuthToken(token);
            if (user == null) {
                return error("Token无效或用户不存在");
            }

            // 生成随机临时秘钥（32位）
            String tempSecret = IdUtils.fastSimpleUUID();
            
            // 设置过期时间（30分钟）
            int expireMinutes = 10;

            // 存储到Redis中
            String redisKey = "temp_secret:" + user.getUserId();
            Map<String, Object> secretInfo = new HashMap<>();
            secretInfo.put("tempSecret", tempSecret);
            secretInfo.put("createTime", System.currentTimeMillis());
            secretInfo.put("userId", user.getUserId());
            // 更新用户表中的tempSecret字段
            SysUser updateUser = new SysUser();
            updateUser.setUserId(user.getUserId());
            updateUser.setTempSecret(tempSecret);
            // 使用updateUserProfile方法，避免删除用户角色关联
            userService.updateUserProfile(updateUser);
            redisCache.setCacheObject(redisKey, secretInfo, expireMinutes, TimeUnit.MINUTES);

            // 返回临时秘钥
            Map<String, Object> result = new HashMap<>();

            result.put("expireTime", expireMinutes * 60); // 返回秒数
            result.put("loginUrl", "http://175.27.248.155/login?redirect=index&tempSecret="+tempSecret); // 返回秒数

            return AjaxResult.success("临时秘钥生成成功").put("data", result);

        } catch (Exception e) {
            logger.error("生成临时秘钥异常", e);
            return error("生成临时秘钥失败：" + e.getMessage());
        }
    }




}
